package com.fubowen.reader.db.service

import com.fubowen.reader.book.impl.Downloader
import com.fubowen.reader.book.impl.TaskGroup
import com.fubowen.reader.book.impl.WebBookGetter
import com.fubowen.reader.book.impl.toTaskList
import com.fubowen.reader.db.bean.BookBean
import com.fubowen.reader.db.dao.BookDao

class BookService(private val bookDao: BookDao) {
    fun setChapterContent(bookId: Int, onCompleted: (TaskGroup) -> Unit = { }) {
        val chapterList = bookDao.getChapterList(bookId, isDownload = false)
        val taskList = chapterList.toTaskList {
            val content = WebBookGetter.getChapterText(url)
            bookDao.setChapterContent(id, content,content.length, isDownload = true)
        }
        Downloader().startGroup(taskList, onCompleted)
    }

    fun setOrGet(model: BookBean): BookBean {
        return bookDao.getByAbsolutePath(model.url) ?: run {
            val id = bookDao.set(model)
            bookDao.get(id.toInt())
        }
    }
}

